package com.zhs.gccs.dao;

import android.content.Context;
import android.database.Cursor;

import com.zhs.gccs.mbtiles.MbtilesDbManager;
import com.zhs.gccs.mbtiles.Tiles;

import org.xutils.DbManager;
import org.xutils.ex.DbException;

public class TilesDao {
    private String dbDir;

    public TilesDao(String dbDir) {
        this.dbDir = dbDir;
    }

    public Tiles find(Context mContext, String dbName, String table, int x, int y, int z) {
        Tiles tiles = null;
        try {//tile_column--》y    tile_row--》x
            DbManager dbManager = MbtilesDbManager.getInstance(mContext)
                    .getDbManager(dbDir,dbName);
            String sql = "select zoom_level,tile_column,tile_row,tile_type,tile_data " +
                    " from "+table+"  " +
                    "where zoom_level = "+z+" and tile_column = "+y+" and tile_row = "+x;
            Cursor cursor = dbManager.execQuery(sql);
            if(cursor!=null&&cursor.moveToFirst()){
                int zoomColumn = cursor.getColumnIndex("zoom_level");
                int zoom = cursor.getInt(zoomColumn);
                int yColumn = cursor.getColumnIndex("tile_column");//y
                int ydata = cursor.getInt(yColumn);
                int xColumn = cursor.getColumnIndex("tile_row");//x
                int xData = cursor.getInt(xColumn);
                int typeColumn = cursor.getColumnIndex("tile_type");
                String type = cursor.getString(typeColumn);
                int dataColumn = cursor.getColumnIndex("tile_data");
                byte[] data = cursor.getBlob(dataColumn);
                tiles = new Tiles(type,zoom,ydata,xData,data);
                cursor.close();
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        return tiles;
    }
}
